package ldh.msg.ui.helper;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class JTextFieldLimit extends PlainDocument {
		  private int limit;
		  private int maxValue;
		  public JTextFieldLimit(int limit, int maxValue) {
		    super();
		    this.limit = limit;
		    if (maxValue < 0) {
		    	this.maxValue = -1;
		    } else {
		    	this.maxValue = maxValue;
		    }
		  }

		  public JTextFieldLimit(int limit, boolean upper) {
		    super();
		    this.limit = limit;
		  }

		  public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
		    if (str == null)
		      return;

		    	if ((getLength() + str.length()) <= limit) {
		    		if (maxValue >= 0) {
				    	int tempInt = Integer.parseInt(getContent().getString(0, getLength()) + str);
//				    	System.out.println("insertString getLength() : " + getLength());
//				    	System.out.println("insertString getContent()() : " + getContent().getString(0, getLength()) + str);
				    	if (tempInt > maxValue) {
//				    		System.out.println("insertString tempInt : " + tempInt);
//				    		System.out.println("insertString maxValue : " + maxValue);
				    		str = Integer.toString(maxValue);
				    		if ((str.length()) <= limit) {
					    		super.replace(0, getLength(), str, attr);
				    		}
				    	} else {
				    		if ((getLength() + str.length()) <= limit) {
						    		super.insertString(offset, str, attr);
						    }
				    	}
				    } else {
				    	super.insertString(offset, str, attr);
				    }
		    }
	}
}